import style from './index.module.scss'
import HeaderView from "@/components/Header"
import { Form, Input, Button, Toast } from 'antd-mobile'
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
import { login } from './type'
import { UserLogin } from '@/api/login'
import { saveToken } from '@/reduxToolkit/reducers/token'
import { cartNumAsync } from '@/reduxToolkit/reducers/cartNum'
import { useDispatch } from 'react-redux'

const Login = () => {
  const dispath: any = useDispatch()
  const navigate = useNavigate()
  const location = useLocation()

  // 提交表单
  const onFinish = async (values: login) => {
    const res = await UserLogin({email: values.email, password: values.password})
    try {
      if(res.status === 200) {
        dispath(saveToken(res.data.access_token))
        dispath(cartNumAsync())
        Toast.show({ icon: 'success', content: '登陆成功', maskClickable: false, afterClose: () => {
          if(location.state === null){
            navigate('/home')
          } else if(location.state.fromPath === 'shopcart') {
            navigate('/shopcart')
          } else if(location.state.fromPath === 'mine') {
            navigate('/mine')
          } else {
            navigate(`${location.state.pathname}?id=${location.state.id}`)
          }
        }})
      }
    } catch (error) {
      console.log(error)
    }
  }  

  return (
    <>
      {/* header信息 */}
      <HeaderView backIcon={false} title='登录中心' backPath=''></HeaderView>

      {/* 登录表单 */}
      <div className={style.box}>
        <Form onFinish={onFinish} layout='horizontal' footer={ 
           <>
            <NavLink to='/register' className={style.link}>注册账号</NavLink>
            <Button block type='submit' size='large' className={style.btn}>登陆</Button>
           </>
        }>
            <Form.Item name='email' label='邮箱' rules={[{ required: true, message: '邮箱不能为空' }]}>
               <Input placeholder='请输入邮箱' />
            </Form.Item>

            <Form.Item name='password' label='密码' rules={[{ required: true, message: '密码不能为空' }]}>
               <Input  placeholder='请输入密码' type='password'/>
            </Form.Item>
        </Form>
      </div>
    </>
  )
}

export default Login